//
//  TWLoginManager.m
//  VFA_QUEUENCE
//
//  Created by Phan Ba Minh on 2/24/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "TWLoginManager.h"
#import "AppViewController.h"
#import "JSON.h"
#import "OAuthTwitter.h"
#import "OAuth.h"
#import "MGTwitterHTTPURLConnection.h"
#import "NSString+SBJSON.h"
#import "OAServiceTicket.h"
#import "OAConsumer.h"
#import "OAToken.h"
#import "MGTwitterRequestTypes.h"
#import "NSData+Base64.h"
#import "NSString+URLEncoding.h"

@implementation TWLoginManager
@synthesize TWController, email, accessToken, loginStatus, name, userName, authData, userID, gender, about;

- (id)initWithConsumerKey:(NSString *)consumerKey andConsumerSecret:(NSString *)consumerSecret {
    self = [super init];
    if (self) {
        // Custom initialization
        _engineSA_OAuthTwitter = [[SA_OAuthTwitterEngine alloc] initOAuthWithDelegate:self];  
        _engineSA_OAuthTwitter.consumerKey    = consumerKey;  
        _engineSA_OAuthTwitter.consumerSecret = consumerSecret;  
        [_engineSA_OAuthTwitter requestRequestToken];
        [_engineSA_OAuthTwitter requestAccessToken];
		
		_APIRequester = [APIRequester new];
        
        _alertViewTWLoginFail = [[UIAlertView alloc] initWithTitle:@"Twitter" message:STRING_TWITTER_MESSAGE_CONNECTION_ERROR delegate:self cancelButtonTitle:STRING_ALERT_OK otherButtonTitles:nil];
    }
    return self;
}

- (void)dealloc {
    RELEASE_SAFE(_engineSA_OAuthTwitter);
    RELEASE_SAFE(TWController);
	RELEASE_SAFE(_APIRequester);
	RELEASE_SAFE(name);
	RELEASE_SAFE(accessToken);
	RELEASE_SAFE(email);
	RELEASE_SAFE(userName);
	RELEASE_SAFE(authData);
    RELEASE_SAFE(userID);
    RELEASE_SAFE(_alertViewTWLoginFail);
    RELEASE_SAFE(gender);
    RELEASE_SAFE(about);
    [super dealloc];
}

static TWLoginManager *m_Instance;
+ (TWLoginManager *)Shared {
    if ( !m_Instance ) {
        m_Instance = [[TWLoginManager alloc] initWithConsumerKey:STRING_TWITTER_APP_KEY andConsumerSecret:STRING_TWITTER_APP_SECRET];
		
		NSData *data = [[NSUserDefaults standardUserDefaults] objectForKey:STRING_USER_DEFAULT_TW_DATA_MANAGER];
        if ([NSKeyedUnarchiver unarchiveObjectWithData:data]) {
            TWLoginManager *_data = [[NSKeyedUnarchiver unarchiveObjectWithData:data] retain];
			m_Instance.name = _data.name;
			m_Instance.email = _data.email;
			m_Instance.accessToken = _data.accessToken;
			m_Instance.loginStatus = _data.loginStatus;
            m_Instance.userName = _data.userName;
            m_Instance.userID = _data.userID;
            m_Instance.gender = _data.gender;
            m_Instance.about  = _data.about;
			[_data release];
        }
    }
    return m_Instance;
}

#pragma mark - Encode - Decode

- (void)encodeWithCoder:(NSCoder *)encoder {
	[encoder encodeObject:userName forKey:STRING_CODER_TW_USER_NAME];
	[encoder encodeObject:name forKey:STRING_CODER_TW_NAME];
	[encoder encodeObject:email forKey:STRING_CODER_TW_EMAIL];
	[encoder encodeObject:accessToken forKey:STRING_CODER_TW_ACCESS_TOKEN];
	[encoder encodeBool:loginStatus forKey:STRING_CODER_TW_LOGIN_STATUS];
    [encoder encodeObject:userID forKey:STRING_CODER_TW_USER_ID];
    [encoder encodeObject:gender forKey:STRING_CODER_TW_GENDER];
    [encoder encodeObject:about forKey:STRING_CODER_TW_ABOUT];
}

- (id)initWithCoder:(NSCoder *)decoder {
    self = [super init];
    if (self) {
		if ([decoder decodeObjectForKey:STRING_CODER_TW_USER_NAME]) self.userName = [decoder decodeObjectForKey:STRING_CODER_TW_USER_NAME];
        if ([decoder decodeObjectForKey:STRING_CODER_TW_NAME]) self.name = [decoder decodeObjectForKey:STRING_CODER_TW_NAME];
        if ([decoder decodeObjectForKey:STRING_CODER_TW_EMAIL]) self.email = [decoder decodeObjectForKey:STRING_CODER_TW_EMAIL];
		if ([decoder decodeObjectForKey:STRING_CODER_TW_ACCESS_TOKEN]) self.accessToken = [decoder decodeObjectForKey:STRING_CODER_TW_ACCESS_TOKEN];
        if ([decoder decodeBoolForKey:STRING_CODER_TW_LOGIN_STATUS]) self.loginStatus = [decoder decodeBoolForKey:STRING_CODER_TW_LOGIN_STATUS];
        if ([decoder decodeObjectForKey:STRING_CODER_TW_USER_ID]) self.userID = [decoder decodeObjectForKey:STRING_CODER_TW_USER_ID];
        if ([decoder decodeObjectForKey:STRING_CODER_TW_GENDER]) self.gender = [decoder decodeObjectForKey:STRING_CODER_TW_GENDER];
        if ([decoder decodeObjectForKey:STRING_CODER_TW_ABOUT]) self.about = [decoder decodeObjectForKey:STRING_CODER_TW_ABOUT];
    }
    return self;
}

- (void)save {
    [[NSUserDefaults standardUserDefaults] setObject:[NSKeyedArchiver archivedDataWithRootObject:self] forKey:STRING_USER_DEFAULT_TW_DATA_MANAGER];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

#pragma mark - TWLoginManager

- (void)changeBackToPreviousViewController {
    //    [self dismissModalViewControllerAnimated:YES];
    
    [[AppViewController Shared] changeBackFromTwitterViewController];
}

- (void)logout
{
	self.loginStatus = NO;
	[self save];
	
    [_engineSA_OAuthTwitter  clearAccessToken];
    [_engineSA_OAuthTwitter setClearsCookies:YES];
    TWController = [SA_OAuthTwitterController controllerToEnterCredentialsWithTwitterEngine:_engineSA_OAuthTwitter delegate:self];
}

- (void)reLogin {
	self.loginStatus = NO;
    
    // Reset authentication of last login if have
    self.authData = nil;
	
    [self save];
	
    [_engineSA_OAuthTwitter  clearAccessToken];
    [_engineSA_OAuthTwitter setClearsCookies:YES];
    TWController = [SA_OAuthTwitterController controllerToEnterCredentialsWithTwitterEngine:_engineSA_OAuthTwitter delegate:self];  
}

- (void)login {
	self.loginStatus = NO;
	[self save];
	
    TWController = [SA_OAuthTwitterController controllerToEnterCredentialsWithTwitterEngine:_engineSA_OAuthTwitter delegate:self];  
}

- (UIViewController *)getTWControllerWithDelegate:(id)idDelegate {
    _delegate = idDelegate;
    
    if (TWController) {
        return TWController;
    }
    return [[UIViewController new] autorelease];//Qasim 7/11/12
}

#pragma mark - SA_OAuthTwitterEngine Protocol

- (void)storeCachedTwitterOAuthData:(NSString *)data forUsername:(NSString *)username {
    NSLog(@"storeCachedTwitterOAuthData data: %@", data);
    NSLog(@"username: %@", username);
    
    if (data && data.length > 0) {
        self.userName = username;
        self.authData = data;
        self.userID = [[[[data componentsSeparatedByString:@"&"] objectAtIndex:2] componentsSeparatedByString:@"="] objectAtIndex:1];
        [self save];
    }
}

- (NSString *)cachedTwitterOAuthDataForUsername:(NSString *)username {
    NSLog(@"cachedTwitterOAuthDataForUsername username: %@", username);
	return authData;
}

- (void)twitterOAuthConnectionFailedWithData:(NSData *)data {
    NSLog(@"twitterOAuthConnectionFailedWithData");
    
    [_alertViewTWLoginFail show];
}

#pragma mark - TwitterEngineDelegate
- (void)OAuthTwitterControllerFailed:(SA_OAuthTwitterController *)controller {
    NSLog(@"OAuthTwitterControllerFailed");
    
    [_alertViewTWLoginFail show];
}

- (void)OAuthTwitterControllerCanceled:(SA_OAuthTwitterController *)controller {
     NSLog(@"OAuthTwitterControllerCanceled");
    
    [self changeBackToPreviousViewController];
}

- (void)OAuthTwitterController:(SA_OAuthTwitterController *)controller authenticatedWithUsername:(NSString *)username {
    NSLog(@"OAuthTwitterController info");
    
    
    [_APIRequester requestWithType:ENUM_API_REQUEST_TYPE_USER_TW_GET_PROFILE andURL:[NSString stringWithFormat:@"https://api.twitter.com/1/users/show.json?screen_name=%@", userName] andDelegate:self];
    
//	self.loginStatus = YES;
//	[self save];
//  [self changeBackToPreviousViewController];
    
}

- (void)requestSucceeded:(NSString *)connectionIdentifier {
	NSLog(@"TW requestSucceeded %@", connectionIdentifier);
}

- (void)requestFailed:(NSString *)connectionIdentifier withError:(NSError *)error {
	NSLog(@"TW requestFailed %@", connectionIdentifier);
    
    [_alertViewTWLoginFail show];
}

#pragma mark - APIRequester Protocol
- (void)requestFailed:(ASIHTTPRequest *)request andType:(ENUM_API_REQUEST_TYPE)type
{
    if (type == ENUM_API_REQUEST_TYPE_USER_TW_GET_PROFILE) {
        NSLog(@"getMyFacebookProfileFail");
        self.loginStatus = NO;
		[self save];
    }
    
    [_alertViewTWLoginFail show];
}
- (void)requestFinished:(ASIHTTPRequest *)request andType:(ENUM_API_REQUEST_TYPE)type
{
    if (type == ENUM_API_REQUEST_TYPE_USER_TW_GET_PROFILE) {
        NSString *responseString = [request responseString];
        NSLog(@"requestFinished: %@",responseString);
        
        NSMutableDictionary *responseJSON = [responseString JSONValue];
        if (responseJSON) {
			self.name = [responseJSON objectForKey:STRING_RESPONSE_KEY_TW_NAME];
			self.gender = [responseJSON objectForKey:STRING_RESPONSE_KEY_TW_GENDER];
            if (self.gender == nil) {
                self.gender = [NSString stringWithFormat:@""];
            }
            self.about = [responseJSON objectForKey:STRING_RESPONSE_KEY_TW_ABOUT];
			if (self.about == nil) {
                self.about = [NSString stringWithFormat:@""];
            }
            
			if (userID && name) {
				self.loginStatus = YES;
				[self save];
                [self changeBackToPreviousViewController];
			}
            else {
                NSLog(@"userID || name = nil");
                self.loginStatus = NO;
                [self save];
                [_alertViewTWLoginFail show];
            }
        }
        else{
            NSLog(@"responseJSON = nil || empty");
            self.loginStatus = NO;
			[self save];
            [_alertViewTWLoginFail show];
        }
    }
}

#pragma mark - UIAlertViewDelegate

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    [self changeBackToPreviousViewController];
}

#pragma mark - Request 

- (void)sendTweet:(NSString*)message andUrl:(NSString*)url andPicture:(UIImage *)picture andDelegate:(id <TWLoginManagerRequesterDelegate>)delegate {
    if(![message isEqualToString:@""]){
        _stringMessageRequester = message;
        _urlRequester = url;
        _imageRequester = picture;
        _delegateRequester = delegate;
    }
    else{
        return;
    }
    
    
    
    //********************CASE 1*******************
//    NSString *boundary = @"----------------------------991990ee82f7";
//    NSURL *finalURL = [NSURL URLWithString:@"http://upload.twitter.com/1/statuses/update_with_media.json"];
//    
//    if (!finalURL) {
//        return;
//    }
//    
//    if(_imageRequester == nil){
//        return;
//    }
//    
//    OAuthTwitter  *oAuthTwitter =  [[OAuthTwitter alloc] initWithConsumerKey:STRING_TWITTER_APP_KEY andConsumerSecret:STRING_TWITTER_APP_SECRET];
//    [oAuthTwitter load];
//    
//    
//    OAConsumer *consumer = [[OAConsumer alloc] initWithKey:STRING_TWITTER_APP_KEY secret:STRING_TWITTER_APP_SECRET];
//    OAToken *token = [[OAToken alloc] initWithKey:oAuthTwitter.oauth_token secret:oAuthTwitter.oauth_token_secret];
//    
//    OAMutableURLRequest *theRequest = [[[OAMutableURLRequest alloc] initWithURL:finalURL
//                                                                       consumer:consumer
//                                                                          token:token
//                                                                          realm: nil
//                                                              signatureProvider:nil] autorelease];
//    
//    [theRequest setHTTPMethod:@"POST"];
//    [theRequest setHTTPShouldHandleCookies:NO];
//    
//    // Set headers for client information, for tracking purposes at Twitter.
//    [theRequest setValue:@"MGTwitterEngine"    forHTTPHeaderField:@"X-Twitter-Client"];
//    [theRequest setValue:@"1.0" forHTTPHeaderField:@"X-Twitter-Client-Version"];
//    [theRequest setValue:@"http://mattgemmell.com/source"     forHTTPHeaderField:@"X-Twitter-Client-URL"];
//    
//    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];
//    [theRequest setValue:contentType forHTTPHeaderField:@"content-type"];
//    
//    NSMutableData *body = [NSMutableData dataWithLength:0];
//    [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
//    
//    [body appendData:[@"Content-Disposition: form-data; name=\"media_data[]\"; filename=\"1.png\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
//    [body appendData:[@"Content-Type: application/octet-stream\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
//    [body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
//    [body appendData:[[UIImageJPEGRepresentation(_imageRequester, 1.0) base64EncodingWithLineLength:0] dataUsingEncoding:NSUTF8StringEncoding]];
//    [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
//    [body appendData:[@"Content-Disposition: form-data; name=\"status\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
//    [body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
//    [body appendData:[[NSString stringWithFormat:@"%@\r\n",message] dataUsingEncoding:NSUTF8StringEncoding]];
//    [body appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
//    
//    // --------------------------------------------------------------------------------
//    // modificaiton from the base clase
//    // our version "prepares" the oauth url request
//    // --------------------------------------------------------------------------------
//    [theRequest prepare];
//
//    [theRequest setHTTPBody:body];
//    
//    // Create a connection using this request, with the default timeout and caching policy,
//    // and appropriate Twitter request and response types for parsing and error reporting.
//    MGTwitterHTTPURLConnection *connection;
//    connection = [[MGTwitterHTTPURLConnection alloc] initWithRequest:theRequest
//                                                            delegate:self
//                                                         requestType:MGTwitterImageRequest
//                                                        responseType:MGTwitterGeneric];
//    
//    if (!connection) {
//        return;
//    } else {
//        //        [_connections setObject:connection forKey:[connection identifier]];
//        [connection release];
//    }
    
//    //********************CASE 2*******************
//    OAuthTwitter  * oAuthTwitter =  [[OAuthTwitter alloc] initWithConsumerKey:STRING_TWITTER_APP_KEY andConsumerSecret:STRING_TWITTER_APP_SECRET];
//    [oAuthTwitter load];
//    
//    ASIFormDataRequest *req = [[ASIFormDataRequest alloc] initWithURL:[NSURL URLWithString:@"http://api.twitpic.com/2/upload.json"]];
//    
//    [req addRequestHeader:@"X-Auth-Service-Provider" value:@"https://api.twitter.com/1/account/verify_credentials.json"];
//    [req addRequestHeader:@"X-Verify-Credentials-Authorization"
//                    value:[oAuthTwitter oAuthHeaderForMethod:@"GET"
//                                                      andUrl:@"https://api.twitter.com/1/account/verify_credentials.json"
//                                                   andParams:nil]];
//    
//    [req setData:UIImageJPEGRepresentation(_imageRequester, 0.8) forKey:@"media"];
//    
//    // Define this somewhere or replace with your own key inline right here.
//    [req setPostValue:STRING_TWITPIC_API_KEY forKey:@"key"];
//    
//    // TwitPic API doc says that message is mandatory, but looks like
//    // it's actually optional in practice as of July 2010. You may or may not send it, both work.
//    [req setPostValue:_stringMessageRequester forKey:@"message"];
//    
//    [req startSynchronous];
//    //    [req setDidFinishSelector:@selector(requestDone:)];
//    //    [req start];
//    
//    NSDictionary *twitpicResponse = [[req responseString] JSONValue];
//    NSLog(@"%@",[NSString stringWithFormat:@"Posted image URL: %@", [twitpicResponse valueForKey:@"url"]]);
//    [req release];
//    
//    NSString *text =@"";
//    if(![(NSString*)[twitpicResponse valueForKey:@"url"] compare:@"(null)"] == 0)
//        text = [twitpicResponse valueForKey:@"url"];
//    else
//        text = nil;
    
    
    NSData *imageData = UIImagePNGRepresentation(_imageRequester);
    NSURL *twitpicURL = [NSURL URLWithString:@"http://twitpic.com/api/uploadAndPost"];
    
    ASIFormDataRequest *request = [[[ASIFormDataRequest alloc] initWithURL:twitpicURL] autorelease];
    
    [request setData:imageData forKey:@"media"];
    [request setPostValue:@"myUsername" forKey:@"username"];
    [request setPostValue:@"myPassword" forKey:@"password"];
    [request setPostValue:@"myMessage" forKey:@"message"];
    
    [request setDelegate:self];
    [request setDidFinishSelector:@selector(requestDone:)];
    [request setDidFailSelector:@selector(requestFailed:)];
    
    [request start];
}

@end
